package service

import (
	"context"
	"dfs/server/worker/api"
	"dfs/server/worker/config"
	"dfs/server/worker/core"
	"fmt"
	"io/ioutil"
	"os"
	"strings"
)

type ClientService struct{}

func (c *ClientService) SaveBlock(ctx context.Context, req *api.SaveBlockReq) (*api.SaveBlockResp, error) {
	if core.GetCap() == 0 {
		return &api.SaveBlockResp{Success: false, Message: "Worker存储空间已满"}, nil
	}
	filePath := fmt.Sprintf("%s/%s-%d.dat", config.PersistURL, strings.ReplaceAll(req.Url, "/", "_"), req.Order)
	file, err := os.Create(filePath)
	if err != nil {
		return &api.SaveBlockResp{Success: false, Message: "创建持久化文件失败"}, nil
	}
	fmt.Fprint(file, string(req.Data))
	file.Close()
	core.CapDecre()
	return &api.SaveBlockResp{Success: true, Message: "存储文件数据块成功"}, nil
}

func (c *ClientService) GetBlock(ctx context.Context, req *api.GetBlockReq) (*api.GetBlockResp, error) {
	filePath := fmt.Sprintf("%s/%s-%d.dat", config.PersistURL, strings.ReplaceAll(req.Url, "/", "_"), req.Order)
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		return &api.GetBlockResp{Success: false, Message: "打开数据块文件失败"}, nil
	}
	return &api.GetBlockResp{Success: true, Message: "获取数据块成功", Data: data}, nil
}

func (c *ClientService) DeleteBlock(ctx context.Context, req *api.DeleteBlockReq) (*api.DeleteBlockResp, error) {
	filePath := fmt.Sprintf("%s/%s-%d.dat", config.PersistURL, strings.ReplaceAll(req.Url, "/", "_"), req.Order)
	err := os.Remove(filePath)
	if err != nil {
		return &api.DeleteBlockResp{Success: false, Message: "删除失败"}, nil
	} else {
		core.CapIncre()
		return &api.DeleteBlockResp{Success: true, Message: "删除数据块成功"}, nil
	}
}
